import efinance as ef
import pathlib
import json
import pandas as pd


class StockUtil:



    # 所有信息
    @staticmethod
    def get_stock_by_code(code):
        # 判断是否存在该code股票
        is_exit = pathlib.Path('web/stockDetail/' + code).exists()
        if is_exit:
            print("该股票已存在")
            return

        # 股票相关信息json
        info_json = {}
        data = ef.stock.get_quote_history(code)
        path = 'web/stockDetail/' + str(code)
        pathlib.Path(path).mkdir(parents=True, exist_ok=True)
        # 保存data.csv
        data.to_csv('web/stockDetail/' + str(code) + "/data.csv")

        chart_data = data.loc[:, ['开盘', '收盘', '最低', '最高']]
        chart_data.to_csv('web/stockDetail/' + str(code) + "/chartData.txt", header=False, index=False)

        chart_time_data = data.loc[:, '日期']
        chart_time_data.to_csv('web/stockDetail/' + str(code) + "/chartTimeData.txt", header=False, index=False)

        ma5 = data['收盘'].rolling(5).mean().round(2)
        ma10 = data['收盘'].rolling(10).mean().round(2)
        ma20 = data['收盘'].rolling(20).mean().round(2)
        ma30 = data['收盘'].rolling(30).mean().round(2)
        ma_data = pd.DataFrame({"MA5": ma5, "MA10": ma10, "MA20": ma20, "MA30": ma30})
        ma_data.to_csv('web/stockDetail/' + code + '/MAData.txt', header=False, index=False)

        # info.json
        info_json["code"] = data.iloc[0]['股票代码']
        info_json['name'] = data.iloc[0]['股票名称']
        info_json["beg"] = data.iloc[0]['日期']
        info_json['end'] = data.iloc[-1]['日期']
        info_json['price'] = data.iloc[-1]['收盘']
        info_file = open(path + '/info.json', mode='w', encoding='utf-8')
        # ensure_ascii=False 代表中文不转义
        json.dump(info_json, info_file, ensure_ascii=False)
        info_file.close()

        # stock.json 更细
        stock_json = {}
        stock_json_file = open("web/json/init_info.json", 'r', encoding='utf-8')
        stock_json = json.load(stock_json_file)
        stock_json_file.close()
        if code in stock_json["stockEnum"]:
            print("该code已存在")
        else:
            stock_json["stockEnum"].append(code)
        stock_json["allStock"][code] = info_json
        print(stock_json)
        with open("web/json/init_info.json", "w", encoding='utf-8') as f:
            json.dump(stock_json, f)
            print("加载入文件完成...")

        return True

    # 获取区间的数据
    @staticmethod
    def get_stock_with_time(code, beg, end):
        data = ef.stock.get_quote_history(code, beg=beg, end=end, klt=101)
        print(data)
        data.to_csv('./web/stockDetail/' + str(code) + "/data.csv")

    # 获取某一年的数据
    @staticmethod
    def get_stock_with_year(code, year):
        beg = str(year) + '0101'
        end = str(year + 1) + '0101'
        data = ef.stock.get_quote_history(str(code), beg=beg, end=end, klt=101)
        print(data)
        data.to_csv('./web/stockDetail/' + str(code) + "/data.csv")
